from collections import deque
class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:

        a=deque()
        e=0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j]==2:
                    a.append((i,j,0))
        while a:
            i,j,c=a.popleft()
            e=c
            lst=[(i,j+1),(i,j-1),(i+1,j),(i-1,j)]
            for d in lst:
                if 0<=d[0]<len(grid) and 0<=d[1]<len(grid[0]):
                    if grid[d[0]][d[1]]==1:
                        grid[d[0]][d[1]]=2
                        a.append((d[0],d[1],c+1))
        
        for ii in grid:
            if 1 in ii:
                e=-1
                break
     
        return e
